<template>
  <view class="container">

    <!-- 表单 -->
    <view class="form-container" v-if="pet">
      <!-- 照片上传 -->
      <view class="photo-section">
        <view class="photo-upload" @click="choosePhoto">
          <image 
            v-if="formData.photo" 
            :src="formData.photo" 
            class="uploaded-photo" 
            mode="aspectFill"
          ></image>
          <view v-else class="upload-placeholder">
            <text class="upload-icon">📷</text>
            <text class="upload-text">点击上传照片</text>
          </view>
        </view>
      </view>

      <!-- 基本信息 -->
      <view class="form-section">
        <!-- 宠物名称（必填） -->
        <view class="form-item">
          <text class="label">宠物名称<text class="required">*</text></text>
          <input 
            v-model="formData.name" 
            placeholder="请输入宠物名称" 
            class="input"
            maxlength="20"
          />
        </view>

        <!-- 宠物类型（必填） -->
        <view class="form-item">
          <text class="label">宠物类型<text class="required">*</text></text>
          <picker 
          :value="typeIndex" 
          :range="petTypeLabels" 
          @change="onTypeChange"
          class="picker"
        >
          <view class="picker-text">
            {{ formData.type || '请选择宠物类型' }}
          </view>
        </picker>
        </view>

        <!-- 品种（必填） -->
        <view class="form-item">
          <text class="label">品种<text class="required">*</text></text>
          <input 
            v-model="formData.breed" 
            placeholder="请输入品种" 
            class="input"
            maxlength="30"
          />
        </view>

        <!-- 其他非必填字段 -->
        <view class="form-item">
          <text class="label">性别</text>
          <picker 
          :value="genderIndex" 
          :range="genderLabels" 
          @change="onGenderChange"
          class="picker"
        >
          <view class="picker-text">
            {{ formData.gender || '请选择性别' }}
          </view>
        </picker>
        </view>

        <view class="form-item">
          <text class="label">生日</text>
          <picker 
            mode="date" 
            :value="formData.birthday" 
            @change="onBirthdayChange"
            class="picker"
          >
            <view class="picker-text">
              {{ formData.birthday || '请选择生日' }}
            </view>
          </picker>
        </view>

        <view class="form-item">
          <text class="label">体重 (kg)</text>
          <input 
            v-model="formData.weight" 
            placeholder="请输入体重" 
            class="input"
            type="digit"
            maxlength="5"
          />
        </view>

        <view class="form-item">
          <text class="label">颜色</text>
          <input 
            v-model="formData.color" 
            placeholder="请输入颜色" 
            class="input"
            maxlength="20"
          />
        </view>

        <view class="form-item">
          <text class="label">备注</text>
          <textarea 
            v-model="formData.remark" 
            placeholder="请输入备注信息" 
            class="textarea"
            maxlength="200"
          />
        </view>
      </view>
    </view>

    <!-- 加载状态 -->
    <view v-else class="loading-container">
      <text class="loading-text">加载中...</text>
    </view>
    
    <!-- 底部保存按钮 -->
    <view class="bottom-save-section" v-if="pet">
      <button class="bottom-save-btn" @click="savePet" :disabled="loading">
        {{ loading ? '保存中...' : '保存' }}
      </button>
    </view>
  </view>
</template>

<script>
import { getPetDetail, updatePet, uploadPetPhoto } from '@/api/pet.js'
import { getToken } from '@/utils/auth.js'
import { getDictData } from '@/api/dict.js'

export default {
  data() {
    return {
      petId: null,
      pet: null,
      formData: {
        name: '',
        type: '',
        breed: '',
        gender: '',
        birthday: '',
        weight: '',
        color: '',
        photo: '',
        remark: ''
      },
      petTypes: [],
      genders: [],
      petTypeLabels: [],
      genderLabels: [],
      typeIndex: -1,
      genderIndex: -1,
      loading: false
    }
  },
  onLoad(options) {
    if (options.id) {
      this.petId = options.id
      this.loadPet()
      this.loadDictData()
    } else {
      uni.showToast({
        title: '参数错误',
        icon: 'none'
      })
      uni.navigateBack()
    }
  },
  methods: {
    async loadPet() {
      this.loading = true
      try {
        uni.showLoading({ title: '加载中...' })
        const response = await getPetDetail(this.petId)
        
        if (response && response.code === 200) {
          this.pet = response.data
          this.initFormData()
        } else {
          uni.showToast({ title: response?.msg || '加载失败', icon: 'none' })
          setTimeout(() => uni.navigateBack(), 1500)
        }
      } catch (error) {
        uni.showToast({ title: '网络错误', icon: 'none' })
        setTimeout(() => uni.navigateBack(), 1500)
      } finally {
        this.loading = false
        uni.hideLoading()
      }
    },
    
    initFormData() {
      if (this.pet) {
        // 处理已存在的照片URL
        let photoUrl = this.pet.photo || ''
        if (photoUrl && !photoUrl.startsWith('http')) {
          const { API_BASE } = require('@/config/config.js')
          if (photoUrl.startsWith('/')) {
            photoUrl = API_BASE + photoUrl
          } else {
            photoUrl = API_BASE + `/profile/upload/${photoUrl}`
          }
        }
        
        this.formData = {
          name: this.pet.name || '',
          type: this.pet.type || '',
          breed: this.pet.breed || '',
          gender: this.pet.gender || '',
          birthday: this.pet.birthday ? this.formatDateForPicker(this.pet.birthday) : '',
          weight: this.pet.weight ? this.pet.weight.toString() : '',
          color: this.pet.color || '',
          photo: photoUrl,
          remark: this.pet.remark || ''
        }
        
        // 设置选择器索引
        this.typeIndex = this.petTypes.findIndex(item => item.dictLabel === this.pet.type)
        this.genderIndex = this.genders.findIndex(item => item.dictLabel === this.pet.gender)
      }
    },
    
    formatDateForPicker(dateString) {
      if (!dateString) return ''
      const date = new Date(dateString)
      return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`
    },
    
    goBack() {
      uni.navigateBack()
    },
    
    choosePhoto() {
      uni.chooseImage({
        count: 1,
        sizeType: ['compressed'],
        sourceType: ['album', 'camera'],
        success: (res) => {
          const localPath = res.tempFilePaths[0]
          // 先本地预览
          this.formData.photo = localPath
          // 上传到服务器
          this.uploadPetPhoto(localPath)
        }
      })
    },
    
    async uploadPetPhoto(filePath) {
      const token = getToken()
      if (!token) {
        uni.showToast({ title: '请先登录', icon: 'none' })
        uni.navigateTo({ url: '/pages/login?from=pet_edit' })
        return
      }
      uni.showLoading({ title: '上传中...' })
      try {
        const data = await uploadPetPhoto(filePath, token)
        if (data && data.code === 200) {
          const photoUrl = data.photoUrl || (data.data && (data.data.photoUrl || data.data.url))
          if (photoUrl) {
            // 处理照片URL - 后端返回的是相对路径，需要拼接完整URL
            let finalPhotoUrl = photoUrl
            
            // 导入API_BASE配置
            const { API_BASE } = require('@/config/config.js')
            
            // 如果后端返回的是 /profile/upload/... 格式，需要拼接API_BASE
            if (photoUrl.startsWith('/profile/')) {
              finalPhotoUrl = API_BASE + photoUrl
            } else if (photoUrl.startsWith('/')) {
              // 其他相对路径，也拼接API_BASE
              finalPhotoUrl = API_BASE + photoUrl
            } else if (!photoUrl.startsWith('http')) {
              // 文件名，拼接完整URL
              finalPhotoUrl = API_BASE + `/profile/upload/${photoUrl}`
            }
            

            
            // 更新表单数据
            this.formData.photo = finalPhotoUrl
            
            // 强制触发页面重新渲染
            this.$forceUpdate()
            
            // 延迟一下再显示成功提示，确保页面更新
            setTimeout(() => {
              uni.showToast({ title: '照片已上传', icon: 'success' })
            }, 100)
            
          } else {
            uni.showToast({ title: '上传成功但未返回地址', icon: 'none' })
          }
        } else {
          uni.showToast({ title: (data && data.msg) || '上传失败', icon: 'none' })
        }
      } catch (error) {
        // 检查是否是网络相关错误
        if (error.errMsg && error.errMsg.includes('fail')) {
          uni.showToast({ title: '网络错误，请检查网络连接', icon: 'none' })
        } else {
          uni.showToast({ title: '上传失败: ' + (error.message || error.errMsg || '未知错误'), icon: 'none' })
        }
      } finally {
        uni.hideLoading()
      }
    },
    
    onTypeChange(e) {
      this.typeIndex = e.detail.value
      this.formData.type = this.petTypes[e.detail.value].dictLabel
    },
    
    onGenderChange(e) {
      this.genderIndex = e.detail.value
      this.formData.gender = this.genders[e.detail.value].dictLabel
    },
    
    onBirthdayChange(e) {
      this.formData.birthday = e.detail.value
    },
    
    validateForm() {
      if (!this.formData.name.trim()) {
        uni.showToast({ title: '请输入宠物名称', icon: 'none' });
        return false;
      }
      if (!this.formData.type) {
        uni.showToast({ title: '请选择宠物类型', icon: 'none' });
        return false;
      }
      if (!this.formData.breed.trim()) {
        uni.showToast({ title: '请输入品种', icon: 'none' });
        return false;
      }
      return true;
    },
    
    async savePet() {
      const token = uni.getStorageSync('token');
      if (!token) {
        uni.showToast({ title: '登录已过期，请重新登录', icon: 'none' });
        setTimeout(() => {
          uni.navigateTo({ url: '/pages/login?from=pet_edit' });
        }, 1500);
        return;
      }
      
      if (!this.validateForm()) {
        return
      }
      
      this.loading = true
      uni.showLoading({
        title: '保存中...'
      })
      
      try {
        // 准备提交数据
        const submitData = {
          name: this.formData.name,
          type: this.formData.type,
          breed: this.formData.breed,
          gender: this.formData.gender,
          birthday: this.formData.birthday,
          weight: this.formData.weight ? parseFloat(this.formData.weight) : null,
          color: this.formData.color,
          photo: this.formData.photo,
          remark: this.formData.remark,
          status: this.pet.status || 'online'
        }
        
        const response = await updatePet(this.petId, submitData)
        
        uni.hideLoading()
        
        if (response && response.code === 200) {
          uni.showToast({
            title: '保存成功',
            icon: 'success'
          })
          
          // 延迟返回上一页
          setTimeout(() => {
            uni.navigateBack()
          }, 1500)
        } else {
          uni.showToast({
            title: response?.msg || '保存失败',
            icon: 'none'
          })
        }
      } catch (error) {
        uni.hideLoading()
  
        uni.showToast({
          title: '网络错误',
          icon: 'none'
        })
      } finally {
        this.loading = false
      }
    }
  },
  
  async loadDictData() {
    try {
      // 加载宠物类型字典
      const petTypeResponse = await getDictData('pet_type')
      if (petTypeResponse && petTypeResponse.code === 200) {
        this.petTypes = petTypeResponse.data || []
        this.petTypeLabels = this.petTypes.map(item => item.dictLabel)
      } else {
        // 默认值
        this.petTypes = [
          { dictLabel: '狗', dictValue: 'dog' },
          { dictLabel: '猫', dictValue: 'cat' },
          { dictLabel: '兔子', dictValue: 'rabbit' },
          { dictLabel: '鸟', dictValue: 'bird' },
          { dictLabel: '鱼', dictValue: 'fish' },
          { dictLabel: '其他', dictValue: 'other' }
        ]
        this.petTypeLabels = this.petTypes.map(item => item.dictLabel)
      }
      
      // 加载宠物性别字典
      const genderResponse = await getDictData('pet_gender')
      if (genderResponse && genderResponse.code === 200) {
        this.genders = genderResponse.data || []
        this.genderLabels = this.genders.map(item => item.dictLabel)
      } else {
        // 默认值
        this.genders = [
          { dictLabel: '公', dictValue: 'male' },
          { dictLabel: '母', dictValue: 'female' }
        ]
        this.genderLabels = this.genders.map(item => item.dictLabel)
      }
      
      // 重新设置选择器索引
      if (this.pet) {
        this.typeIndex = this.petTypes.findIndex(item => item.dictLabel === this.pet.type)
        this.genderIndex = this.genders.findIndex(item => item.dictLabel === this.pet.gender)
      }
      
    } catch (error) {

      // 使用默认值
      this.petTypes = [
        { dictLabel: '狗', dictValue: 'dog' },
        { dictLabel: '猫', dictValue: 'cat' },
        { dictLabel: '兔子', dictValue: 'rabbit' },
        { dictLabel: '鸟', dictValue: 'bird' },
        { dictLabel: '鱼', dictValue: 'fish' },
        { dictLabel: '其他', dictValue: 'other' }
      ]
      this.petTypeLabels = this.petTypes.map(item => item.dictLabel)
      this.genders = [
        { dictLabel: '公', dictValue: 'male' },
        { dictLabel: '母', dictValue: 'female' }
      ]
      this.genderLabels = this.genders.map(item => item.dictLabel)
      
      // 重新设置选择器索引
      if (this.pet) {
        this.typeIndex = this.petTypes.findIndex(item => item.dictLabel === this.pet.type)
        this.genderIndex = this.genders.findIndex(item => item.dictLabel === this.pet.gender)
      }
    }
  }
}
</script>

<style scoped>
.container {
  background: #f5f5f5;
  min-height: 100vh;
}

.nav-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx;
  background: #fff;
  border-bottom: 1px solid #eee;
}

.back-btn {
  background: #007AFF;
  color: #fff;
  border: none;
  border-radius: 8rpx;
  padding: 10rpx 30rpx;
  font-size: 28rpx;
}

.title {
  font-size: 32rpx;
  font-weight: bold;
}

.form-container {
  padding: 20rpx;
  padding-bottom: 120rpx; /* 为底部固定按钮留出空间 */
}

.loading-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 400rpx;
}

.loading-text {
  font-size: 28rpx;
  color: #999;
}

.photo-section {
  background: #fff;
  border-radius: 15rpx;
  padding: 30rpx;
  margin-bottom: 20rpx;
}

.photo-title {
  font-size: 30rpx;
  font-weight: bold;
  margin-bottom: 20rpx;
  color: #333;
}

.photo-upload {
  width: 200rpx;
  height: 200rpx;
  border: 2px dashed #ddd;
  border-radius: 50%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  margin: 0 auto; /* 居中显示 */
  overflow: hidden; /* 确保图片不超出圆形边框 */
}

.uploaded-photo {
  width: 100%;
  height: 100%;
  border-radius: 50%;
  object-fit: cover; /* 确保图片填充整个圆形区域 */
}

.upload-placeholder {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.upload-icon {
  font-size: 60rpx;
  margin-bottom: 10rpx;
}

.upload-text {
  font-size: 24rpx;
  color: #999;
}

.form-section {
  background: #fff;
  border-radius: 15rpx;
  padding: 30rpx;
}

.form-item {
  display: flex;
  align-items: center;
  margin-bottom: 30rpx;
}

.label {
  width: 180rpx; /* 固定标签宽度 */
  flex-shrink: 0;
  font-size: 28rpx;
  color: #333;
  font-weight: bold;
}

.required {
  color: #ff4d4f; /* 红色星号 */
  margin-left: 5rpx;
}

.input, .picker {
  flex: 1;
  min-height: 36rpx;
  padding: 20rpx;
  border: 1px solid #ddd;
  border-radius: 8rpx;
  font-size: 28rpx;
  background: #fff;
}

.picker-text {
  color: #333;
}

.textarea {
  height: 120rpx;
  resize: none;
}

.input:focus, .textarea:focus {
  border-color: #007AFF;
}

.bottom-save-section {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background: #fff;
  padding: 20rpx;
  border-top: 1px solid #eee;
  box-shadow: 0 -2rpx 10rpx rgba(0,0,0,0.1);
}

.bottom-save-btn {
  width: 100%;
  background: #007AFF;
  color: #fff;
  border: none;
  border-radius: 10rpx;
  padding: 25rpx;
  font-size: 32rpx;
  font-weight: bold;
}

.bottom-save-btn:disabled {
  background: #ccc;
  color: #999;
}

.bottom-save-btn:active {
  background: #0056b3;
}
</style>
